/**
 * Created by chuchuang on 16/10/26.
 */
$(function () {
    var $group_Id = $("#groupId").val();
    var $tea_Id = $("#teaId").val();
    var $count = '';
    var $teaName = '';

    function one() {
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: '/group/groupMessage',
            data: {
                groupID: $group_Id
            },
            success: function (result) {
                if (result.success) {
                    $count = result.data.count;
                    $("#groupNumber").attr("value", result.data.count);
                    if ($issueID == null || $issueID == '' || $issueID == undefined){
                        if ($count != 0) {
                            if ($count > 0) {
                                for (var i = 0; i < $count; i++) {
                                    $from.taskList.push($(taskFrom()));
                                }
                            }
                            refurbishTask();
                        }
                    }
                }
            }
        });

        $.ajax({
            type: 'post',
            dataType: 'json',
            url: '/identity/id/' + $tea_Id,
            success: function (result) {
                if (result.success) {
                    $teaName = result.data.name;
                    $("#teaName").attr("value", result.data.name);
                }
            }
        });
    }


    var technologyMap;
    var $issueId = $("#issueIdDiv");
    var $issueID = $("#issue_company_id").val();
    var dataFrom = {
        issue: {
            technology: []
        },
        issueContent: {
            outTeacher: {},
            taskList: []
        }
    };
    var $from = {
        technologyList: [],
        taskList: []
    };

    function refurbishTask() {
        var taskGroup = $("#group_rw");
        taskGroup.html("");
        $.each($from.taskList, function (i, node) {
            taskGroup.append(node);
        })
    }

    function init() {
        $from.issueTitle = $("input[name='issueTitle']");
        $from.issueKind = $("select[name='issueKind']");
        $from.issueTypeSelect = $("#issueTypeSelect");
        $from.issueType = $("input[name='issueType']");
        $from.issueType.val("设计");
        $from.issueOutTea = $("input[name='outTeaName']");

        $from.issueTypeSelect.change(function () {
            if ($(this).val() == '其他') {
                $from.issueType.val("");
                $from.issueType.show();
            } else {
                $from.issueType.val($(this).val());
                $from.issueType.hide();
            }
        });
        $from.issueBackground = $("textarea[name='issueBackground']");
        refurbishTask()
    }


    //刷新技术领域
    function refurbishTechnology() {
        $("#jsly").html("");
        $.each($from.technologyList, function (i, n) {
            n.change(function () {
                if (n.attr("checked")) {
                    n.attr("checked", false);
                } else {
                    n.attr("checked", true);
                }
            });
            $("#jsly").append(n);
        });
    }

    function technologyLabelInit() {
        return "<label><input type='checkbox' value=''/></label>";
    }

    function taskFrom() {
        return "<div class='rwbt'> " +
            "<div class='form-group'> " +
            "<label class='col-sm-2 control-label'>任务</label> " +
            "<div class='col-sm-7'> " +
            "<input name='taskTitle' type='text' placeholder='子标题' class='form-control'> " +
            "</div> " +
            "</div> " +
            "<div class='form-group'>" +
            "<label class='col-sm-2 control-label'>任务分工</label>" +
            "<div class='col-sm-7'> " +
            "<textarea name='taskContent' style='height: 150px;' placeholder='任务分工' class='form-control'>" +
            "</textarea> " +
            "</div> " +
            "</div> " +
            "</div>"
    }


    function saveIssue() {
        $from.issueKind.val(dataFrom.issue.kind);
        $from.issueType.val(dataFrom.issue.type);
        $from.issueTitle.val(dataFrom.issue.title);
        $from.issueBackground.val(dataFrom.issueContent.background);
        $from.issueOutTea.val(dataFrom.issueContent.outTeacher.name);
        $from.taskList = [];

        if ($from.issueTypeSelect.val() == dataFrom.issue.type) {
            $from.issueType.hide();
        } else {
            $from.issueTypeSelect.val("其他");
            $from.issueType.show();
        }

        $.each(dataFrom.issueContent.taskList, function (i, node) {
            var task = $(taskFrom());
            $(task.find("input[name='taskTitle']")).val(node.title);
            $(task.find("textarea[name='taskContent']")).val(node.content);
            $from.taskList.push(task);
        });
        if ($from.technologyList != null) {
            $.each($from.technologyList, function (i, node) {
                if (dataFrom.issue.technology != null) {
                    $.each(JSON.parse(dataFrom.issue.technology), function (j, tech) {
                        // alert(node+"<br>"+tech);
                        var red = $(node.find("input"));
                        if (red.val() == tech.id) {
                            red.attr("checked", 'checked');
                        }
                    })
                }
            });
        }
    }

    // 初始加载
    $(function () {
        one();
        init();
        $.ajax({
            url: "/issue/gainTechnologyAll",
            type: "POST",
            dataType: "json",
            success: function (data) {
                if (data.success) {
                    technologyMap = data.data;
                    for (var key in technologyMap) {
                        var $technologyLabel = $(technologyLabelInit());
                        $($technologyLabel.find("input")).val(key);
                        $($technologyLabel.append(technologyMap[key].title));
                        $from.technologyList.push($technologyLabel);
                    }
                    refurbishTechnology();
                } else {
                    alert(data.errorMsg)
                }
            }
        });
        //根据用户ID 查询题目信息
        if ($issueId.find("input[name='issueId']").val() > 0) {
            $.ajax({
                url: "/issue/" + $issueId.find("input[name='issueId']").val(),
                dataType: "json",
                type: "GET",
                success: function (result) {
                    if (result.success) {
                        dataFrom = result.data;
                        saveIssue();
                        // refurbishTechnology()
                        refurbishTask();
                    } else {
                        alert(result.errorMsg);
                    }
                }
            });
        }
    });


    function validationFrom() {
        var flag = true;
        if (dataFrom.issue.title == null || dataFrom.issue.title.trim() == '') {
            alert("请输入标题名称");
            flag = false;
        }
        if (dataFrom.issueContent.background == null || dataFrom.issueContent.background.trim() == '') {
            alert("请输入项目背景");
            flag = false;
        }

        if (dataFrom.issueContent.taskList.length == 1) {
            if ((dataFrom.issue.title + dataFrom.issueContent.taskList[0].title).length > 25) {
                alert("标题名称与子标题的长度总和超过25,无法保存");
                flag = false;
            }
            if (dataFrom.issueContent.taskList[0].content == null || dataFrom.issueContent.taskList[0].content.trim() == '') {
                alert("请输入任务详情");
                flag = false;
            }
            return flag;
        }

        $.each(dataFrom.issueContent.taskList, function (i, node) {
            if (node.title == null || node.title.trim() == '') {
                alert("请输入第" + (i + 1) + "个子标题");
                flag = false;
            } else if ((dataFrom.issue.title + node.title).length > 25) {
                alert("标题名称与第" + (i + 1) + "个子标题的长度超过25,无法保存");
                flag = false;
            }
            if (node.content == null || node.content.trim() == '') {
                alert("请输入第" + (i + 1) + "个任务详情");
                flag = false;
            }
        });
        return flag;
    }

    function getTaskList() {
        dataFrom.issueContent.taskList = [];
        $.each($from.taskList, function (i, node) {
            var task = {title: "", content: ""};
            if ($(node.find("input[name='taskTitle']")).val() != null) {
                task.title = $(node.find("input[name='taskTitle']")).val();
            }
            task.content = $(node.find("textarea[name='taskContent']")).val();
            dataFrom.issueContent.taskList.push(task);
        });
    }

    function getTechnology() {
        dataFrom.issue.technology = [];
        if (dataFrom.issue.technology != null) {
            $.each($from.technologyList, function (i, node) {
                var check = $(node.find("input"));
                if (check.attr("checked")) {
                    var technology = {id: 0, title: ""};
                    technology.id = check.val();
                    technology.title = node.text();
                    dataFrom.issue.technology.push(technology);
                }
            });
        }
    }

    function getOutTeacher() {
        var $name = '';
        if ($("input[name='outTeaName']").val() != null) {
            $name = $("input[name='outTeaName']").val();
        }
        dataFrom.issueContent.outTeacher.name = $name;
    }

    function createSub() {
        getTaskList();
        getTechnology();
        getOutTeacher();
        // $from.issueKind
        dataFrom.issue.kind = $from.issueKind.val();
        dataFrom.issue.taskSize = $from.taskList.length;
        dataFrom.issue.type = $from.issueType.val();
        dataFrom.issue.title = $from.issueTitle.val();
        dataFrom.issue.schoolTeaId = $tea_Id;
        dataFrom.issue.schoolTeaName = $teaName;
        dataFrom.issueContent.background = $from.issueBackground.val();
    }






    $("submit").click(function () {
        createSub();
        // alert(JSON.stringify(dataFrom));
        if (!validationFrom()) {
            return false;
        }
        if ($issueId.find("input[name='issueId']").val() == '') {
            $.ajax({
                url: "/issue",
                type: "POST",
                data: {
                    jsonData: JSON.stringify(dataFrom)
                },
                dataType: "json",
                success: function (result) {
                    if (result.success) {
                        window.location.href = '/stu/stuGroup'
                    } else {
                        alert(result.errorMsg);
                    }
                }
            });
        } else {
            $.ajax({
                url: "/issue/" + $issueId.find("input[name='issueId']").val(),
                type: "POST",
                data: {
                    jsonData: JSON.stringify(dataFrom)
                },
                dataType: "json",
                success: function (result) {
                    if (result.success) {
                        window.location.href = '/stu/stuGroup';
                    } else {
                        alert(result.errorMsg);
                    }
                }
            });
        }

        return false;
    });

});